package com.normalClasses.eye;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.corpus.tag.Nature;
import com.hankcs.hanlp.seg.common.Term;

public class Key_word_similar{
	private String comparison_object1;//比较字符串1
	private String comparison_object2;//比较字符串2
	private List<Term> object1_keyword;//关键词list
	private List<Term> object2_keyword;//关键词list
	private List<Term> comparison_set;//整合分词向量词组
	private int[] object1_vector;//词频矢量
	private int[] object2_vector;//词频矢量
	private float res_data;
public Key_word_similar(String comparison_object1,String comparison_object2){
	// TODO Auto-generated constructor stub
	this.comparison_object1=comparison_object1;
	this.comparison_object2=comparison_object2;
	//第一步，获取关键分词
	object1_keyword=HanLP.segment(this.comparison_object1);
	object2_keyword=HanLP.segment(this.comparison_object2);
	//System.out.println(object1_keyword);
	//System.out.println(object2_keyword);
	//第二步，将词组融合，列出所有词
	this.comparison_set=new ArrayList<Term>();
	
	for(int i = 0;i<object1_keyword.size();i++){
		if(!this.comparison_set.contains(object1_keyword.get(i))){
			comparison_set.add(object1_keyword.get(i));
		}
	}
	for(int i = 0;i<object2_keyword.size();i++){
		if(!this.comparison_set.contains(object2_keyword.get(i))){
			comparison_set.add(object2_keyword.get(i));
		}
	}
	
	//第三步，分词编码+词频矢量化
	object1_vector=new int[comparison_set.size()];//创建矢量
	object2_vector=new int[comparison_set.size()];//创建矢量
	//迭代遍历set
	Iterator it=comparison_set.iterator();
	int index=0;//矢量的索引
	while(it.hasNext()){
		Term keyword=(Term) it.next();
		//遍历1字符
		for(int i=0,j=0;i<object1_keyword.size();i++){
			Term current=object1_keyword.get(i);
			if(current.equals(keyword)){
				j++;
			}
			if(i==object1_keyword.size()-1) {
				object1_vector[index]=j;
			}
		}
		//遍历2字符
		for(int i=0,j=0;i<object2_keyword.size();i++) {
			Term current=object2_keyword.get(i);
			if(current.equals(keyword)){
				j++;
			}
			if(i==object2_keyword.size()-1){
				object2_vector[index]=j;
			}
		}
	     index++;	
	}
	//第四步，余弦相似计算
	 this.res_data=this.Cosine_calculation(object1_vector,object2_vector);
}
//余弦计算
 public float Cosine_calculation(int[] a, int [] b){
	 int dot_product=0;
	 float a_modulus_value=0,b_modulus_value=0;//初始化模值
	 //计算内积 
	 for(int i=0;i<a.length;i++){
		 dot_product=dot_product+a[i]*b[i];		 
	 }
	 //计算a&&b的模值
	 for(int i=0;i<a.length;i++){
     a_modulus_value=a_modulus_value+a[i]*a[i];
     b_modulus_value=b_modulus_value+b[i]*b[i];
     }
	 //开根号
	 a_modulus_value=(float)java.lang.Math.sqrt(a_modulus_value);
	 b_modulus_value=(float)java.lang.Math.sqrt(b_modulus_value);
	 return dot_product/(a_modulus_value*b_modulus_value); 
}
//获取计算结果
  public float getRes_data() {
	return this.res_data;
  }
  public List<Term> getComparison_set(){
	return this.comparison_set;  
  }
}
